const express = require("express")
const bodyParser = require("body-parser")

const cookieParser = require("cookie-parser")

const expressSession = require("express-session")
const uuid = require("uuid")
const cors = require("cors")
let app = express()
app.use("*", (request, response, next) => {
    //请求的路径带 api的字眼
    if (request.originalUrl.indexOf("/api") != -1) {
        response.setHeader("Content-type", "application/json;charset=utf-8");
    }

    next();
})


app.use(cors());
app.use(express.static("./../src/"))
app.use(expressSession({
    genid: function() {
        return uuid.v1()
    },
    maxAge: 1000 * 60 * 20,
    secret: "1000phone",
    resave: true,
    saveUninitialized: true

}))

app.use(cookieParser("1000phone"))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
    // 开始

let whiteList = ["/api/login", "/api/reg", "/api/goodsById", "/api/goodslist"]


app.use("*", (request, response, next) => {


    if (request.originalUrl == "/favicon.ico") {
        return;
    }

    if (request.originalUrl.indexOf("/api") != -1) {
        response.setHeader("Content-type", "application/json;charset=utf-8");
    }
    if (request.session["userInfo"] == undefined || request.session["userInfo"] == null) {

        let isPass = whiteList.some(el => {
            console.log(111);

            console.log(request.originalUrl.toLowerCase());
            return request.originalUrl.toLowerCase().indexOf(el.toLowerCase()) != -1

        })

        console.log(isPass);
        if (isPass) {

            next();
        } else {
            response.json({
                err: "请先登录",
                status: -1
            })
        }
    } else {
        next();
    }
})

// 结束













app.use("/api", require("./routes/apiRoute"))

app.listen(8080, function() {
    console.log("服务启动完毕");
})